import { defineStore } from 'pinia'
import service, { UserRole } from 'src/api/service'

/* table的类型 */

// 整体加载表
export interface totalTable {
  status: 'init' | 'loading' | 'total' | 'error'
}

// 累计加载表
export interface partTable {
  status: 'init' | 'loading' | 'part' | 'error'
}

// id
export interface idTable<T> {
  allIds: string[]
  byId: Record<string, T>
}

// localId
export interface localIdTable<T> {
  allLocalIds: string[]
  byLocalId: Record<string, T>
}

export const useStore = defineStore('main', {
  state: () => ({
    items: {
      // 实时记录用户所在app局部路径位置
      // 例如'/my/server/personal/list' -> ['personal', 'list'], 供二级三级导航栏在刷新时保持选择使用
      currentPath: [] as string[]
    },
    user: {
      id: '',
      username: '',
      fullname: '',
      telephone: '',
      company: '',
      role: '' as UserRole, // 'admin' | 'regular'
      status: '',
      isAdmin: false,
      loaded: false
    }
  }),
  getters: {
    // 检查用户是否已加载
    isUserLoaded: (state) => state.user.loaded,
    // 检查用户是否为管理员
    isUserAdmin: (state) => state.user.isAdmin
  },
  actions: {
    // 加载当前用户信息
    async loadUserInfo () {
      try {
        const response = await service.txMeeting.getPersonalMeetingUserInfo()
        const userData = response.data

        this.user.id = userData.user.id
        this.user.username = userData.user.username
        this.user.fullname = userData.user.fullname
        this.user.telephone = userData.user.telephone
        this.user.company = userData.user.company
        this.user.role = userData.role
        this.user.status = userData.status
        this.user.isAdmin = userData.role === 'admin'
        this.user.loaded = true

        return userData
      } catch (error) {
        console.error('Failed to load user info:', error)
        throw error
      }
    }
  }
})
